package org.example.test;
import javax.swing.plaf.nimbus.AbstractRegionPainter;
import java.util.*;
/**
 * @author: lynn
 * @Descript:
 * @date: 2021/8/1 16:07
 * @version: 1.0
 */
public class ThreeSum {

    public static void main(String[] args) {

        ThreeSum ts=new ThreeSum();
        int[] nums={-2,0,1,1,2};
        System.out.println(ts.threeSum(nums));

    }

    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res=new ArrayList();
        Arrays.sort(nums);
        for (int k = 0; k <nums.length ; k++) {
            if (nums[0]>0) break;
            if (k>0&&nums[k]==nums[k-1]) continue;
            int l=k+1;
            int r=nums.length-1;
            while (l<r){
                int sum=nums[k]+nums[l]+nums[r];
                if (sum<0) {
                    while (l<r && nums[l]==nums[++l]);
                }else if (sum>0){
                    while(l<r && nums[r]==nums[--r]);
                }else{
                    res.add(new ArrayList<>(Arrays.asList(nums[l],nums[r],nums[k])));
                    while (l<r && nums[l]==nums[++l]);
                    while (l<r && nums[r]==nums[--r]);
                }
            }
        }
        return res;
    }
}
